/*
 * devtool.html -> devtool.js -> start.html -> ui.js
 * ui.js is to create tooldev tab(Papa) to manage sitemaps
 * It loads data from db when ui.js inits and persist data to db by each 'save' action.
 */
//Config
var readFromDB = true;
 
 
//init template
var roadmapTemplate = $('#roadmapTemplate').html();
var selTableTemplate = $('#selTableTemplate').html();
var selFormTemplate = $('#selFormTemplate').html();
var pageTableTemplate = $('#pageTableTemplate').html();
var pageFormTemplate = $('#pageFormTemplate').html();
var pagingTemplate = $('#pagingTemplate').html();
var fieldTableTemplate = $('#fieldTableTemplate').html();
var fieldFormTemplate = $('#fieldFormTemplate').html();
var linkFormTemplate = $('#linkFormTemplate').html();
var linkTableTemplate = $('#linkTableTemplate').html();
Mustache.parse(roadmapTemplate);
Mustache.parse(selTableTemplate);
Mustache.parse(selFormTemplate);
Mustache.parse(pageTableTemplate);
Mustache.parse(pageFormTemplate);
Mustache.parse(pagingTemplate);
Mustache.parse(fieldTableTemplate);
Mustache.parse(fieldFormTemplate);
Mustache.parse(linkFormTemplate);
Mustache.parse(linkTableTemplate);

function hideAll(){
//	$('#roadmapTable').hide();
	$('#pagingForm').hide();
	$('#selContainer').hide();
	$('#pageContainer').hide();
	$('#fieldContainer').hide();
	$('#linkContainer').hide();
}

//hide other tables
hideAll();

var data, curSitemap, curSel, curPage, curField, curLink;
var curSelector; 

//select one page
function findPage(id){
	curPage = curSitemap.pages.find(function(p){return p.id == id})
}

Roadmap = {
	list: function(){
		$('#roadmapTable').show().html(Mustache.render(roadmapTemplate, data));
		roadmapTableEvent();
	},
	
	//select one roadmap
	find: function(name){
		curSitemap = data.sitemaps.find(function(sm){return sm.name == name})
		$('#pageContainer').show();
		$('#pageTable').html(Mustache.render(pageTableTemplate, curSitemap));
		$('#pageForm').html(Mustache.render(pageFormTemplate, {s: curSitemap.selectors.filter(function(s){return !s.row})}));
		pageTableEvent();
		$('#roadmapTable').hide();
	},
	
	//create empty roadmap
	createRoadmap: function(name){
		curSitemap = new Sitemap();
		curSitemap.name = name;
		data.sitemaps.push(curSitemap);
		curSitemap.id = data.sitemaps.length;
		$('#pageContainer').show();
		$('#pageTable').html(Mustache.render(pageTableTemplate, curSitemap));
		$('#pageForm').html(Mustache.render(pageFormTemplate, {s: []}));
		pageTableEvent();
		$('#roadmapTable').hide();
	},
	
	remove: function(name){
		var index = data.sitemaps.findIndex(function(sm){return sm.name == name});
		data.sitemaps.splice(index, 1);
		$('#roadmapTable').html(Mustache.render(roadmapTemplate, data));
		roadmapTableEvent();
	}
}

//selector
Sel = {
	//show table
	list: function(name){
		event.stopPropagation();
		curSitemap = data.sitemaps.find(function(sm){return sm.name == name})
		$('#selContainer').show()
		$('#selTable').html(Mustache.render(selTableTemplate, {ss: curSitemap.selectors.filter(function(s){return !s.row})}));
		$('#selForm').html(Mustache.render(selFormTemplate, {ss: curSitemap.selectors.filter(function(s){return !s.row})}));
		selContainerEvent();
		$('#roadmapTable').hide();
		WRITE();
	},
	
	//edit selector
	edit: function(id){
		if(!id){
			curSel = null;
			$('#selForm').html(Mustache.render(selFormTemplate, {ss: curSitemap.selectors.filter(function(s){return !s.row})}));
			return;
		}
		curSel = curSitemap.selectors.find(function(s){return s.id == id});
		var ss = [];
		curSitemap.selectors
			.filter(function(s){return !s.row})
			.forEach(function(e){if(id != e.id){ss.push(e)}})
		$('#selForm').html(Mustache.render(selFormTemplate, {curSel: curSel, ss: ss}));
		if(curSel.parentElement){
			$('#parentSels').val(curSel.parentElement.id);
		}
	},
	
	//save selector form
	save: function(){
		if(!curSel){
			curSel = new PapaElement();
			curSel.id = curSitemap.nextSelectorId();
			curSitemap.selectors.push(curSel);
		}
		curSel.name = $('#selName').val();
		curSel.selector = $('#selSelector').val();
		var pId = $('#parentSels').val();
		if(pId){
			curSel.parentElement = curSitemap.selectors.find(function(s){return s.id == pId});
		}
		$('#selTable').html(Mustache.render(selTableTemplate, {ss: curSitemap.selectors.filter(function(s){return !s.row})}));
		selContainerEvent();
		WRITE();
	},
	
	//delete selector
	remove: function(id){
		event.stopPropagation();
		var index;
		for (var i = 0; i < curSitemap.selectors.length; i++) {
			var f = curSitemap.selectors[i];
			if(f.id == id){
				index = i;
				break;
			}
		}
		curSitemap.selectors.splice(index, 1);
		curSel = null;
		$('#selForm').html(Mustache.render(selFormTemplate, {ss: curSitemap.selectors.filter(function(s){return !s.row})}));
		$('#selTable').html(Mustache.render(selTableTemplate, curSitemap));
		selContainerEvent();
		WRITE();
	},
	
	//go back to sitemap list
	toSitemap: function(){
		Roadmap.list();
		$('#selContainer').hide();
	}	
}
Page = {
	//edit page
	edit: function(id){
		if(id == null){
			curPage = null;
			$('#pageForm').html(Mustache.render(pageFormTemplate, {s: curSitemap.selectors.filter(function(s){return !s.row})}));
			return;
		}
		findPage(id);
		$('#pageForm').show().html(Mustache.render(pageFormTemplate, {p: curPage, s: curSitemap.selectors.filter(function(s){return !s.row})}));
		var p = curPage.rowElement.parentElement;
		if(p){
			$('#pageForm .selectors').val(p.id + '');
		}
	},
	
	//save page form
	save: function(){
		if(!curPage){
			curPage = new SourcePage();
			curPage.id = curSitemap.nextPageId();
			curSitemap.pages.push(curPage);
		}
		curPage.name = $('#name').val();
		curPage.link = $('#link').val();
		var rowElement = curPage.rowElement;
		if(!rowElement){
			rowElement = new PapaElement();
			rowElement.id = curSitemap.nextSelectorId();
			rowElement.row = true;
			curSitemap.selectors.push(rowElement); //register in selectors
			curPage.rowElement = rowElement;
		}
		rowElement.selector = $('#rowElement').val();
		var pe = $('#pageForm .selectors').val();
		if(pe){
			rowElement.parentElement = curSitemap.selectors.find(function(s){return s.id == parseInt(pe)});
		}
		
		$('#pageTable').html(Mustache.render(pageTableTemplate, curSitemap));
		pageTableEvent();
		WRITE();
	},
	
	//delete page
	remove: function(id){
		event.stopPropagation();
		findPage(id);
		var pages = curSitemap.pages, index;
		for (var i = 0; i < pages.length; i++) {
			if(pages[i] == curPage){
				index = i;
				break;
			}
		}
		pages.splice(index, 1);
		$('#pageTable').html(Mustache.render(pageTableTemplate, curSitemap));
		pageTableEvent();
		WRITE();
	},
	
	toSitemap: function(){
		Roadmap.list();
		$('#pageContainer').hide();
	}
}

Pagings = {
	//edit paging
	edit: function(id){
		event.stopPropagation();
		findPage(id);
		$('#pagingForm').show().html(Mustache.render(pagingTemplate, {p: curPage, s: curSitemap.selectors.filter(function(s){return !s.row})}));
		pagingFormEvent();
		if(curPage.paging && curPage.paging.nextPageElement){
			var p = curPage.paging.nextPageElement.parentElement;
			if(p){
				$('#pagingForm .selectors').val(p.id + '');
			}
			$('#pagingType').val(curPage.paging.type);
		}
		$('#pageContainer').hide();
	},
	
	//save paging form
	save: function(){
		var p = curPage.paging;
		if(p == null){
			p = new Paging();
			curPage.paging = p;
		}
		p.type = $('#pagingType').val();
		var nextPageElement = {
			selector: $('#nextPageElement').val()
		}
		var pe = $('#pagingForm .selectors').val();
		if(pe){
			nextPageElement.parentElement = parseInt(pe);
		}
		p.nextPageElement = new PapaElement(nextPageElement, curSitemap);
		
		$('#pageContainer').show();
		$('#pagingForm').hide();
		WRITE();
	},
	//cancel page form
	cancel: function(){
		$('#pageContainer').show();
		$('#pagingForm').hide();
	}
}
Field = {
	//show table
	list: function(id){
		event.stopPropagation();
		findPage(id);
		$('#fieldContainer').show()
		$('#fieldTable').html(Mustache.render(fieldTableTemplate, curPage));
		$('#fieldForm').html(Mustache.render(fieldFormTemplate, {p:curPage.rowElement}));
		fieldContainerEvent();
		$('#pageContainer').hide();
	},
	
	//edit field
	edit: function(title){
		if(!title){
			curField = null;
			$('#fieldForm').html(Mustache.render(fieldFormTemplate, {p:curPage.rowElement}));
			fieldFormEvent();
			return;
		}
		curField = curPage.fields.find(function(f){return f.title == title});
		$('#fieldForm').html(Mustache.render(fieldFormTemplate, {f:curField, p:curPage.rowElement}));
		if(curField.element.contentExtractor){
			with(curField.element.contentExtractor){
				$('#extractorType').val(type);
				$('#extractorAttr').val(attr).get(0).disabled = (type == 'text');
				$('#extractorProcess').val(process);
			}
			
		}
		$('#unique')[0].checked = curField.unique;
		fieldFormEvent();
	},
	
	//save field form
	save: function(){
		if(!curField){
			curField = new PapaField();
			curPage.fields.push(curField);
		}
		curField.title = $('#fieldTitle').val();
		curField.unique = $('#unique')[0].checked;
		var contentExtractor = {
			type: $('#extractorType').val(),
			attr: $('#extractorAttr').val(),
			process: $('#extractorProcess').val()
		}
		var fieldElement = {
			selector: $('#fieldSelector').val(),
			contentExtractor: contentExtractor
		}
		curField.element = new PapaElement(fieldElement, curSitemap);
		$('#fieldTable').html(Mustache.render(fieldTableTemplate, curPage));
		fieldTableEvent();
		WRITE();
	},
	
	//delete field
	remove: function(title){
		event.stopPropagation();
		var index;
		for (var i = 0; i < curPage.fields.length; i++) {
			var f = curPage.fields[i];
			if(f.title == title){
				index = i;
				break;
			}
		}
		curPage.fields.splice(index, 1);
		curField = null;
		$('#fieldForm').html(Mustache.render(fieldFormTemplate, {}));
		$('#fieldTable').html(Mustache.render(fieldTableTemplate, curPage));
		fieldContainerEvent();
		WRITE();
	},
	
	//go back to page list
	toPage: function(){
		$('#fieldContainer').hide()
		$('#pageContainer').show();
	}
}
Link = {
	//show table
	list: function(id){
		event.stopPropagation();
		findPage(id);
		$('#linkContainer').show()
		$('#linkTable').html(Mustache.render(linkTableTemplate, curPage));
		$('#linkForm').html(Mustache.render(linkFormTemplate, {pp: Link._getPages(), p:curPage.rowElement}));
		linkContainerEvent();
		$('#pageContainer').hide();
	},
	
	//edit link
	edit: function(id){
		if(!id){
			curLink = null;
			$('#linkForm').html(Mustache.render(linkFormTemplate, {pp: Link._getPages(), p:curPage.rowElement}));
			return;
		}
		curLink = curPage.linkedPages.find(function(f){return f.sourcePage.id == id});
		
		var pp = Link._getPages();
		$('#linkForm').html(Mustache.render(linkFormTemplate, {l: curLink, pp: pp, p: curPage.rowElement}));
		$('#linkPage').val(id);
	},
	
	//save link form
	save: function(){
		if(!curLink){
			curLink = new LinkedPage();
			curPage.linkedPages.push(curLink);
		}
		var paging = {
			type: $('#linkType').val(),
			nextPageElement: {
				selector: $('#linkElement').val()
			}
		}
		curLink.paging = new Paging(paging, curSitemap);
		curLink.sourcePage = curSitemap.pages.find(function(_p){
			return _p.id == $('#linkPage').val();
		});
		$('#linkTable').html(Mustache.render(linkTableTemplate, curPage));
		linkContainerEvent();
		WRITE();
	},
	
	//delete link
	remove: function(id){
		event.stopPropagation();
		var index;
		for (var i = 0; i < curPage.linkedPages.length; i++) {
			var f = curPage.linkedPages[i];
			if(f.sourcePage.id == id){
				index = i;
				break;
			}
		}
		curPage.linkedPages.splice(index, 1);
		curLink = null;
		$('#linkForm').html(Mustache.render(linkFormTemplate, {pp: Link._getPages()}));
		$('#linkTable').html(Mustache.render(linkTableTemplate, curPage));
		linkContainerEvent();
		WRITE();
	},
	
	//go back to page list
	toPage: function(){
		$('#linkContainer').hide()
		$('#pageContainer').show();
	},
	
	//get page list for selection
	_getPages: function(){
		var pp = [];
		curSitemap.pages.forEach(function(p){
			if(p.id != curPage.id){
				pp.push(p);
			}
		})
		return pp;
	}
}

//onclick property is invalid in devtool html
//init event after template created
var roadmapTableEvent = function(){
	$('.roadmap').click(function(){
		Roadmap.find($(this).attr('data-param'));
	});
	$('.sel-list').click(function(){
		Sel.list($(this).attr('data-param'));
	})
	$('.roadmap-add').click(function(){
		var name = $('#new-roadmap-name').val();
		if(name != ''){
			Roadmap.createRoadmap(name);
		}
	});
	$('.sel-remove').click(function(){
		Roadmap.remove($(this).attr('data-param'));
	});
	$('.sel-start').click(function(){
		var roadmapName = ($(this).attr('data-param'));
		print("====start====" + roadmapName);
		chrome.runtime.sendMessage({
			cmd: 'START_SCRAPE',
			tabId: chrome.devtools.inspectedWindow.tabId,
			params: {
				sitemap: roadmapName
			}
		});
	});
	
}
var selContainerEvent = function(){
	$('.sel-edit').click(function(){
		Sel.edit(parseInt($(this).attr('data-param')));
	});
	$('.sel-remove').click(function(){
		Sel.remove(parseInt($(this).attr('data-param')));
	});
}
var pageTableEvent = function(){
	$('.page-edit').click(function(){
		Page.edit(parseInt($(this).attr('data-param')));
	});
	$('.page-remove').click(function(){
		Page.remove(parseInt($(this).attr('data-param')));
	});
	$('.paging-edit').click(function(){
		Pagings.edit(parseInt($(this).attr('data-param')));
	});
	$('.field-list').click(function(){
		Field.list(parseInt($(this).attr('data-param')));
	});
	$('.link-list').click(function(){
		Link.list(parseInt($(this).attr('data-param')));
	});
}
var pagingFormEvent = function(){
	$('.paging-save').click(Pagings.save);
	$('.paging-cancel').click(Pagings.cancel);
}

var fieldTableEvent = function(){
	$('.field-edit').click(function(){
		Field.edit($(this).attr('data-param'));
	});
	$('.field-remove').click(function(){
		Field.remove($(this).attr('data-param'));
	});
}
var fieldFormEvent = function(){
	$('#extractorType').change(function(){
		this.nextElementSibling.disabled = (this.value == 'text');
	});
}
var fieldContainerEvent = function(){
	fieldTableEvent();
	fieldFormEvent();
}
var linkContainerEvent = function(){
	$('.link-edit').click(function(){
		Link.edit(parseInt($(this).attr('data-param')));
	});
	$('.link-remove').click(function(){
		Link.remove(parseInt($(this).attr('data-param')));
	});
}

//Start
$(function(){
	//init event
	$('.sel-new').click(function(){Sel.edit()});
	$('.sel-save').click(Sel.save);
	$('.sel-toSitemap').click(Sel.toSitemap);
	$('.page-new').click(function(){Page.edit()});
	$('.page-save').click(Page.save);
	$('.page-toSitemap').click(Page.toSitemap);
	$('.field-new').click(function(){Field.edit()});
	$('.field-save').click(Field.save);
	$('.field-toPage').click(Field.toPage);
	$('.link-new').click(function(){Link.edit()});
	$('.link-save').click(Link.save);
	$('.link-toPage').click(Link.toPage);
	$('body').on('click', '.selector', function(){
		curSelector = this;
		var pSelector;
		var pselectorEle = $(this).parent().find('.pselector');
		var isRowSelector = this.id == 'rowElement';
		if(pselectorEle.size()){
			var pId = pselectorEle.val();
			pSelector = curSitemap.selectors.find(function(s){return s.id == pId});
			//lookup each rowElement
			if(!pSelector){
				var page = curSitemap.pages.find(function(p){return p.rowElement && (p.rowElement.id == pId)});
				pSelector = page && page.rowElement;
			}
		}
		chrome.runtime.sendMessage({
			cmd: 'START_SELECT',
			tabId: chrome.devtools.inspectedWindow.tabId,
			params: {
				multi: isRowSelector ? 1 : 0,
				selector: curSelector.value,
				scope: pSelector && pSelector.toString()
			}
		});
	})
	
	if(chrome.storage && readFromDB){ //adapt if devtool environment
		//init sitemap from db
		chrome.storage.local.get("sitemaps", function(db){
			var _sitemaps = db["sitemaps"];
			if(_sitemaps){
				print(JSON.stringify(_sitemaps));
				data = {sitemaps: _sitemaps.map(function(s){return new Sitemap(s)})};
			}else{
				data = {sitemaps:[new Sitemap(sitemap)]};
			}
			
			//load roadmap table
			Roadmap.list();
		});
	}else{
		data = {sitemaps:[new Sitemap(sitemap[1])]};
		Roadmap.list();
	}
	
	//event
	chrome.runtime.connect({
	    name: "devtools-papa"
	}).onMessage.addListener(function (msg) {
	    var p = msg.params;
		if(msg.cmd == 'END_SELECT'){
			curSelector.value = msg.params.selector;
		}
	});
	
})

var WRITE = function(){
	var db = {'sitemaps': data.sitemaps.map(function(s){return s.toDB()})};
	console.log(JSON.stringify(db));
	if(chrome.storage){ //adapt if devtool environment
		chrome.storage.local.set(db, function(){
	      console.log('Saved sitemap');
	    });
	}
}

var print = function(msg){
	if(chrome.storage){
		sendMessage({
			cmd: 'LOG',
			params: msg
		})
	}else{
		console.log(msg);
	}
}
var sendMessage = function(msg){
	chrome.runtime.sendMessage(msg);
}



